(function($){
    var client = new com.im.common.ajax();
    var loading = false;
    var param = {"pageInfo":{"pageNumber":1,"pageSize":10}};

    var methods = {
        init: function(options) {
            var o = $.extend({
                elmIdModal : "userSearchModal",//需要展示的位置
                elmIdOrgModal : "unitSearchModal",//需要展示的位置
                elmIdOut : "userOut",//单击时回填的文本框
                callbackFunc: function(staffId,staffName) {
                }
            }, options || {});

            var self = this;

            onInit(o);

            return this;
        },
        treeOnClickInner : function(self,opt){
            //加载数据
            return o.treeOnClick('1','test');
        }

    };

    function onInit(opt) {
        //渲染查询界面
        _render(opt);


    };



    function _render(opt){
        //获取模态框
        var modal = $("#"+opt.elmIdModal);
        //清空
        modal.empty();
        var pDiv = $($.parseHTML('  <div class="modal-dialog modal-lg myModal_lg" role="document">' +
            '    <div class="modal-content">' +
            '      <div class="modal-header">' +
            '        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
            '        <h4 class="modal-title">用户搜索</h4>' +
            '      </div>' +
            '      <div class="modal-body modalGrayBg">' +
            '        <!--内容开始-->' +
            '        <div class="box box-default">' +
            '          <div class="box-header with-border">' +
            '            <div class="row">' +
            '              <div class="col-md-12">' +
            '' +
            '                <div class="form-inline">' +
            '                       <!--' +
            '                             <div class="form-group">' +
            '                                 <label for="exampleInputName2">单位：</label>' +
            '                               <div class="input-group">' +
            '                                    <input id="exampleInputName2" type="text" class="form-control" placeholder="请搜索单位" disabled="true"></input>' +
            '                                    <span class="input-group-btn">' +
            '                                  <button id="searchOrgBtn" class="btn btn-default" type="button"><i class="fa fa-search"></i></button>' +
            '                                </span>' +
            '                                </div>' +
            '                            </div>-->' +
            '                    <div class="form-group">' +
            '                        <label for="unitTypeSel">单位类型：</label>' +
            '                        <div class="input-group">' +
            '                            <select id="comp_user_unit_type_sel" class="form-control"></select>' +
            '                        </div>' +
            '                    </div>' +
            '                    <div class="form-group">' +
            '                        <label for="unitSel">单位：</label>' +
            '                        <div class="input-group">' +
            '                            <select id="comp_user_unit_sel" class="form-control"></select>' +
            '                       </div>' +
            '                   </div>' +
            '                  <div class="form-group">' +
            '                    <label>用户名称：</label>' +
            '                    <input id="comp_user_user_name_input" type="text" class="form-control" placeholder="请输入用户名称"/>' +
            '                  </div>' +
            '                  <button id="comp_user_search_btn" type="submit" class="btn btn-info"><i class="fa fa-search"></i> 查询</button>' +
            '                </div>' +
            '' +
            '              </div>' +
            '            </div>' +
            '          </div>' +
            '              <div class="box-body">' +
            '                <div class="col-sm-2 noLeftPadding">' +
            '                  <div class="treeMenu">' +
            '                    <ul id="comp_user_org_tree_ul" class="easyui-tree">' +
            '                    </ul>' +
            '                  </div>' +
            '                </div>' +
            '                <div class="myTable">' +
            '                  <table id="comp_user_user_list_info_tab" class="table table-bordered table-striped">' +
            // '                    <thead>' +
            // '                      <tr>' +
            // '                        <th class="fontCenter">选择</th>' +
            // '                        <th>序号</th>' +
            // '                        <th>登录账号</th>' +
            // '                        <th>用户名称</th>' +
            // '                        <th>手机号码</th>' +
            // '                        <th>联系电话</th>' +
            // '                        <th>电子邮箱</th>' +
            // '                        <th>单位</th>' +
            // '                        <th class="fontCenter">状态</th>' +
            // '                      </tr>' +
            // '                    </thead>' +
            // '                    <tbody id="projectUserListTBody">' +
            // '                    </tbody>' +
            '                  </table>' +
            '                  <div class="myPage">' +
            '                    <div id="comp_user_page_div"></div>' +
            '                  </div>' +
            '                </div>' +
            '              </div>' +
            '        </div>' +
            '      <!--内容结束-->' +
            '      </div>' +
            '' +
            '      <div class="modal-footer">' +
            '        <button id="comp_user_cancel_btn" type="button" class="btn btn-default">关闭</button>' +
            '        <button id="comp_user_ensure_btn" type="button" class="btn btn-primary">确定</button>' +
            '      </div>' +
            '    </div>' +
            '  </div>'));
        modal.append(pDiv);
        $("#"+opt.elmIdModal).modal("show");
        //初始化组织树
        $("#comp_user_user_list_info_tab").unitCommpent({
            elmId: "comp_user_org_tree_ul",//组织树显示的<ul>元素id
            elmIdOut: null,//组织树单击之后回填的文本框（input）
            hasOrgType: true,//组织树是否先展示组织类型
            treeOnClick: function (orgId, orgName) {//组织树单击之后回调函数
                //单击之后查询用户
                param.orgId = orgId;
                _doSearchPage(1,param);
            }
        });
        //初始化组织查询按钮
        $("#comp_user_org_search_btn").click(function () {
            $("#comp_user_org_out_input").unitSearchCommpent({
                elmIdOut : "comp_user_org_out_input",//组织树单击之后回填的文本框（input）
                elmIdModal : opt.elmIdOrgModal,
                hasOrgType: true,//组织树是否先展示组织类型
                callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
                    //_callBackOrg(orgId, orgName);
                    param.orgId = orgId;
                    _doSearchPage(1,param);
                }
            });
        });

        //查询用户
        $("#comp_user_search_btn").click(function () {
           param.staffName = $("#comp_user_user_name_input").val();
           _doSearchPage(1,param);
        });
        //确认
        $("#comp_user_ensure_btn").click(function () {
            _returnFunc(opt);
        });
        //
        $("#comp_user_cancel_btn").click(function () {
            $("#"+opt.elmIdModal).empty();
            $("#"+opt.elmIdModal).modal("hide");
        });
        //
        $("#"+opt.elmIdModal).on('shown.bs.modal', function () {
            //初始化组织下拉框
            $(this).unittypeToSelCommpent({
                elmIdTypeSel : "comp_user_unit_type_sel",//需要展示的位置下拉框
                elmIdSel : "comp_user_unit_sel",//需要展示的位置下拉框
                callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
                    param.orgId = objvalue;
                    _doSearchPage(1,param);
                }
            });
        });

    };
    function _doSearchPage(index,param){

        param.pageInfo.pageNumber = index;
        param.staffName = $("#comp_user_user_name_input").val();

        //初始化权限菜单
        var result = client.callAsJson("userService/queryStaffsByCond", param);
        if (result.success) {
            if(result.result != null){
                _showUserListUi(index,result.result);
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    }

    function _showUserListUi(idx,result){
        var columns=[[
            {field:'staffId',title:'',width:40,fitColumns:true,
            formatter: function(value,row,index){
            return  '<input type="checkbox" name="comp_user_chose_r" class="minimal" value='+index+'></input>';
             }},
            {field:'staffCode',title:"登录账号",width:100,fitColumns:true},
           // {field:'staffPwd',title:"登录密码",width:100,fitColumns:true},
            {field:'name',title:"用户名称",width:100,fitColumns:true},
            {field:'mobilePhone',title:"手机号码",width:100,fitColumns:true},
            {field:'linkTel',title:"联系电话",width:100,fitColumns:true},
            {field:'email',title:"电子邮箱",width:100,fitColumns:true},
            {field:'orgName',title:"单位",width:100,fitColumns:true},
            {field:'statusCd',title:"状态Cd",width:100,fitColumns:true,hidden:true},
            {field:'statusName',title:"状态",width:100,fitColumns:true}
        ]];

        $("#comp_user_user_list_info_tab").datagrid({
    	    nowrap:false,
    	    fitColumns:true,
            columns : columns,
            data : result.rows,
            onClickRow : function(idx){
                com.im.common.util.onClickRowCom({elmTable:"comp_user_user_list_info_tab",rowIndex:idx});
            }
        });

        //页码
        $("#comp_user_page_div").pagination({
            total : result.total,
            pageSize : result.pageSize,
            pageNumber : result.pageNumber,
            pageList : [10 , 20],
            beforePageText:  '第' ,
            afterPageText: '页 共'+result.totalPages+'页',
            displayMsg: '共 '+result.total+'条记录',
            onSelectPage: function (pageNumber, pageSize) {
                param.pageInfo.pageNumber = pageNumber;
                param.pageInfo.pageSize = pageSize;
                _doSearchPage(pageNumber,param);
            }
        });

        //设置radio事件，因为会执行onClickRow，所以radio单机事件处理为不做任何变化，避免冲突
        $("input[name=comp_user_chose_r]").click(function () {
            var c = $(this).prop("checked");
            if(c){
                $(this).prop("checked",false);
            }else{
                $(this).prop("checked",true);
            }
        });
    };

    function _returnFunc(opt){
        var staffId = $("input[name='comp_user_chose_r']:checked").val();
        if(staffId != undefined){
            var staff = $('#comp_user_user_list_info_tab').datagrid('getData').rows[staffId];
            if(opt.elmIdOut != null && opt.elmIdOut != undefined){
                $("#"+opt.elmIdOut).val(staff.name);
                $("#"+opt.elmIdOut).attr("staffId",staff.staffId);
            }
            //清除
            $("#"+opt.elmIdModal).empty();
            $("#"+opt.elmIdModal).modal("hide");
            return opt.callbackFunc(staff.staffId,staff.name,staff.mobilePhone,staff.staffCode);
        }else{
            toastr.warning("您未选择任何用户!!");
        }
    };
    
    $.fn.userSearchCommpent = function(method) {

        if (methods[method] && method.charAt(0) != '_') {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.pagination');
        }
    };

})(jQuery);